package com.wlbx.agent.ui.activity;

import android.app.KeyguardManager;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.security.keystore.KeyProperties;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;
import androidx.core.os.CancellationSignal;

import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.fingerprint.CryptoObjectHelper;
import com.wlbx.agent.util.fingerprint.MyAuthCallback;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.KeyGenerator;

import butterknife.BindView;
import butterknife.OnClick;

public class FinglePrintActivity extends BaseActivity {
    private static final String TAG = "FinglePrintActivity";

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;
    @BindView(R.id.iv_sw)
    ImageView mSwIV;

    //指纹
    private PopupWindow mPopupFingerPrintWindow;
    private Handler mHandler = new Handler();
    private KeyStore mKeyStore;
    private KeyGenerator mKeyGenerator;
    private Handler handler;
    private FingerprintManagerCompat fingerprintManager;
    private MyAuthCallback myAuthCallback;
    private CancellationSignal cancellationSignal;
    public static final int MSG_AUTH_SUCCESS = 100;
    public static final int MSG_AUTH_FAILED = 101;
    public static final int MSG_AUTH_ERROR = 102;
    public static final int MSG_AUTH_HELP = 103;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fingleprint;
    }

    @Override
    public void initData() {
        mTitleTV.setText("指纹");
        String fingerprint = (String)SPUtil.get("fingerprint","0");
        if("0".equals(fingerprint)){
            mSwIV.setImageResource(R.mipmap.sw_close);
            mSwIV.setTag("close");
        }else{
            mSwIV.setImageResource(R.mipmap.sw_open);
            mSwIV.setTag("open");
        }
    }

    @Override
    public void initEvent() {}

    @OnClick({R.id.iv_layout_top_back,R.id.iv_sw})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                finish();
                break;
            case R.id.iv_sw:
                if("close".equals(mSwIV.getTag())) {
                    if(supportFingerprint(this)) {
                        mHandler.postDelayed(mRunnable, 500);
                    }
                }else{
                    mSwIV.setImageResource(R.mipmap.sw_close);
                    mSwIV.setTag("close");
                    SPUtil.put("fingerprint","0");
                }
                break;
            default:
                break;
        }
    }
    //校验当前设备是否支持指纹
    public static boolean supportFingerprint(Context mContext) {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(mContext, "您的系统版本过低，不支持指纹功能", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            KeyguardManager keyguardManager = mContext.getSystemService(KeyguardManager.class);
            FingerprintManagerCompat fingerprintManager = FingerprintManagerCompat.from(mContext);
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(mContext, "您的系统版本过低，不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (keyguardManager != null && !keyguardManager.isKeyguardSecure()) {
                Toast.makeText(mContext, "您的手机不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(mContext, "您至少需要在系统设置中添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    private void initFingerPrint(){
        //读取指纹设置
        if (mPopupFingerPrintWindow != null && mPopupFingerPrintWindow.isShowing()) {
            mPopupFingerPrintWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_fingerprint_login, null);
            mPopupFingerPrintWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupFingerPrintWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        }
    }

    private void initFingure() {
        fingerprintManager = FingerprintManagerCompat.from(this);
        if (!fingerprintManager.isHardwareDetected()) {
            Toast.makeText(mContext,"您的设备上没有指纹传感器，点击取消退出",Toast.LENGTH_SHORT).show();
        } else if (!fingerprintManager.hasEnrolledFingerprints()) {
            Toast.makeText(mContext,"没有指纹登记，请到设置->安全中设置",Toast.LENGTH_SHORT).show();
        } else {
            try {
                setFingurePws();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    private void setFingurePws() {
        // TODO Auto-generated method stub
        try {
            mKeyStore = KeyStore.getInstance("AndroidKeyStroe");
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStroe");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }

        initFingerPrint();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_AUTH_SUCCESS:
                        setResultInfo("SUCCESS");
                        cancellationSignal = null;
                        break;
                    case MSG_AUTH_FAILED:
                        setResultInfo("指纹识别失败");
                        cancellationSignal = null;
                        break;
                    case MSG_AUTH_ERROR:
                        handleErrorCode(msg.arg1);
                        break;
                    case MSG_AUTH_HELP:
                        handleHelpCode(msg.arg1);
                        break;
                }
            }
        };
        myAuthCallback = new MyAuthCallback(handler);
        try {
            CryptoObjectHelper cryptoObjectHelper = new CryptoObjectHelper();
            if (cancellationSignal == null) {

                cancellationSignal = new CancellationSignal();
            }
            fingerprintManager.authenticate(cryptoObjectHelper.buildCryptoObject(),0, cancellationSignal, myAuthCallback, null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(FinglePrintActivity.this, "指纹识别初始化失败，请重试！", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleErrorCode(int code) {
        switch (code) {
            case FingerprintManager.FINGERPRINT_ERROR_USER_CANCELED:
            case FingerprintManager.FINGERPRINT_ERROR_CANCELED:
                mPopupFingerPrintWindow.dismiss();
                mSwIV.setImageResource(R.mipmap.sw_close);
                mSwIV.setTag("close");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE:
                setResultInfo("硬件不可用，请稍后再试");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_LOCKOUT:
                setResultInfo("LOCKED");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_NO_SPACE:
                setResultInfo("无法完成操作，因为还没有足够的存储空间来完成操作");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_TIMEOUT:
                setResultInfo("操作超时，请重试");
                break;
            case FingerprintManager.FINGERPRINT_ERROR_UNABLE_TO_PROCESS:
                setResultInfo("指纹图像无法识别，请重试");
                break;
        }
    }

    private void setResultInfo(String stringId) {
        if ("SUCCESS".equals(stringId)) {
            Toast.makeText(FinglePrintActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
            mPopupFingerPrintWindow.dismiss();
            mSwIV.setImageResource(R.mipmap.sw_open);
            mSwIV.setTag("open");
            SPUtil.put("fingerprint","1");
        }else if("LOCKED".equals(stringId)){
            mSwIV.setImageResource(R.mipmap.sw_close);
            mSwIV.setTag("close");
            if(cancellationSignal!=null){
                cancellationSignal.cancel();
                cancellationSignal = null;
            }
            mPopupFingerPrintWindow.dismiss();

        }else{
            Toast.makeText(FinglePrintActivity.this, stringId, Toast.LENGTH_SHORT).show();
        }


    }


    private void handleHelpCode(int code) {
        switch (code) {
            case FingerprintManager.FINGERPRINT_ACQUIRED_GOOD:
                setResultInfo("获得的图像是好的");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_IMAGER_DIRTY:
                setResultInfo("由于传感器上的可疑或检测到的灰尘，指纹图像太嘈杂了。");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_INSUFFICIENT:
                setResultInfo("指纹图像太嘈杂了");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_PARTIAL:
                setResultInfo("请紧按指纹传感器");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_TOO_FAST:
                setResultInfo("手指移动过快");
                break;
            case FingerprintManager.FINGERPRINT_ACQUIRED_TOO_SLOW:
                setResultInfo("请移动手指");
                break;
        }
    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            initFingure();
        }
    };
}